<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    .box{width:100px;height:100px;position: absolute;left:0;top:0;background: red;}
  </style>
</head>
<body>
  <div class="box"></div>
</body>
<script>

  var box = document.querySelector(".box")

  var speed = 100;

  document.onkeydown = function(eve){
    var e = eve || window.event;
    var code = e.keyCode || e.which;

    // 根据方向键，移动元素
    switch(code){
      case 37:
        box.style.left = box.offsetLeft - speed + "px";
        break;
      case 38:
        box.style.top = box.offsetTop - speed + "px";
        break;
      case 39:
        box.style.left = box.offsetLeft + speed + "px";
        break;
      case 40:
        box.style.top = box.offsetTop + speed + "px";
        break;
    }

  }
  
</script>
</html>